<template>
	<view class="login-page">
		<view class="login-logo">
			<cover-image src="../../static/logo.png"></cover-image>
		</view>
		<view class="login-hi">
			<text>早上好</text>
			<cover-image src="../../static/hi.png"></cover-image>
		</view>
		<view class="login-warp">
			<uni-forms class="login-form" :model-value="loginForm" ref="form" :rules="rules">
				<uni-forms-item name="email">
					<uni-easyinput class="login-input" :inputBorder="false" maxlength="50" trim="all"
						v-model="loginForm.email" placeholder="账号"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="pwd">
					<uni-easyinput class="login-input" :inputBorder="false" maxlength="30" type="password" trim="all"
						v-model="loginForm.pwd" placeholder="密码"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item>
					<button class="login-button" hover-class="login-button-hover" @click="handleLogin">登 录</button>
				</uni-forms-item>
				<uni-forms-item>
					<view class="form-bottom">
						<navigator url="/pages/register/register" open-type="redirect">用户注册</navigator>
						<navigator url="/pages/forget/forget" open-type="redirect">找回密码</navigator>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted } from 'vue';
	import { LOGIN_FORM_RULES } from '../../common/static.data'
	import request from '../../common/request';
	
	const form = ref()
	const loginForm = reactive({
		email: '670746668@qq.com',
		pwd: '123x'
	})
	const rules = LOGIN_FORM_RULES

	const handleLogin = async () => {
		try {
			let validData = await form.value?.validate()
			console.log(validData)
			
			try {
				uni.showLoading({ title: '加载中...', mask: true })
				let result = await request.post('/login', validData)
				const { code, msg, data } = result
				if (code) {
					uni.setStorageSync('token', data.token)
					uni.setStorageSync('userInfo', data.userInfo)
					
					await request.ws('/login', data.token)
				}
				uni.showToast({
					title: msg,
					icon: 'success'
				})
				uni.hideLoading()
			} catch (e) {
				console.error(e)
				uni.showToast({
					title: e['msg'].errMsg || '登录失败',
					icon: 'error'
				})
				uni.hideLoading()
			}
		} catch (e) {
			console.error(e)
		}
	}
	
	onMounted(async () => {
		// 清除数据缓存
		uni.clearStorageSync()
		// websocket login result
		request.onWs((result) => {
			console.log(result)
			if (result.url === '/login' && result.data.code) {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		})
	})
</script>

<style>
</style>